﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;

namespace XDA_ROM_Hub
{
    public partial class Troubleshooting : Form
    {
        private Thread thrDownload;
        private Stream strResponse;
        private Stream strLocal;
        private HttpWebRequest webRequest;
        private HttpWebResponse webResponse;
        private static int PercentProgress;
        private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);
        bool goPause = false;
        bool downloaded = false;

        public Troubleshooting()
        {
            InitializeComponent();
            UserClosing = false;
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
        }

        public bool UserClosing { get; set; }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            switch (e.CloseReason)
            {
                case CloseReason.ApplicationExitCall:
                    break;
                case CloseReason.FormOwnerClosing:
                    break;
                case CloseReason.MdiFormClosing:
                    break;
                case CloseReason.None:
                    break;
                case CloseReason.TaskManagerClosing:
                    break;
                case CloseReason.UserClosing:
                    if (UserClosing)
                    {
                        cencelbtn();
                    }
                    else
                    {
                        cencelbtn();
                    }
                    break;
                case CloseReason.WindowsShutDown:
                    break;
                default:
                    break;
            }
        }

        public void cencelbtn()
        {
            this.Hide();

        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (downloaded == false)
            {
                if (thrDownload != null && thrDownload.ThreadState == ThreadState.Running)
                {
                    MessageBox.Show("A download is already running. Please either the stop the current download or await for its completion before starting a new one.", "Download in progress", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Downloading... Click ok and wait for another message box.");
                    thrDownload = new Thread(new ParameterizedThreadStart(Download));
                    thrDownload.Start(0);

                }
            }
            else if (downloaded == true)
            {
                System.Diagnostics.ProcessStartInfo p = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + @"\Drivers.exe");
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = p;

                proc.Start();
                proc.WaitForExit();

                MessageBox.Show("Finished!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }
        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
            if (PercentProgress == 100)
            {
                MessageBox.Show("Please click Install Drivers again.");
                downloaded = true;
                button1.Enabled = true;
            }
            else { button1.Text = "Downloading..."; button1.Enabled = false; }
        }
        private void Download(object startPoint)
        {
            try
            {
                int startPointInt = Convert.ToInt32(startPoint);
                webRequest = (HttpWebRequest)WebRequest.Create("http://xperiaromhub.fav.cc/other/drivers.exe");
                webRequest.AddRange(startPointInt);

                webRequest.Credentials = CredentialCache.DefaultCredentials;
                try
                {
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("This file is yet to be uploaded, please try again later.\nError: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Int64 fileSize = webResponse.ContentLength;

                strResponse = webResponse.GetResponseStream();

                if (startPointInt == 0)
                {
                    strLocal = new FileStream(Application.StartupPath+@"\Drivers.exe", FileMode.Create, FileAccess.Write, FileShare.None);
                }
                else
                {
                    strLocal = new FileStream(Application.StartupPath + @"\Drivers.exe", FileMode.Append, FileAccess.Write, FileShare.None);
                }

                int bytesSize = 0;
                byte[] downBuffer = new byte[2048];

                while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    strLocal.Write(downBuffer, 0, bytesSize);
                    this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize + startPointInt });

                    if (goPause == true)
                    {
                        break;
                    }
                }
            }
            finally
            {
                strResponse.Close();
                strLocal.Close();
            }
        }

        private void Troubleshooting_Load(object sender, EventArgs e)
        {

        }
    }
}
